package com.example.apidemo.login;

import com.example.apidemo.net.Result;
import com.example.apidemo.login.bean.User;
import com.example.apidemo.sql.UserService;
import com.example.apidemo.util.JwtUtils;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;


////接口调用层

@RestController
@RequestMapping("/api")
public class UserController {
    private final UserService userService;

    @Autowired
    public UserController(UserService userService) {
        this.userService = userService;
    }


    // 查找所有用户
    @PostMapping("/login")
    //@ResponseBody
    public Result getLogin(@RequestParam("name") String name, @RequestParam("tel") String tel) {

        System.out.println("name:" + name + "tel:" + tel);

        if (userService.getlogin(name, tel)) {

            Map<String, Object> umap = new HashMap<>();
            umap.put("name", name);
            umap.put("tel", tel);

            String token = JwtUtils.generateJwt(umap);

            return new Result().success("登录成功" + token);
        } else {
            return new Result().error("用户名或密码错误");
        }

        //return new Result().success(userService.getAllUsers());
    }


    ///获取访问对象的ip地址
    @GetMapping("/aip")
    public Result getAip(HttpServletRequest request) {
        String ipAddress = request.getHeader("X-Forwarded-For");
        if (ipAddress == null) {
            ipAddress = request.getRemoteAddr();
        }
        System.out.println("IP Address: " + ipAddress);
        return new Result().success("IP Address: " + ipAddress);
    }

    // 查找所有用户
    @GetMapping("/all")
    //@ResponseBody
    public Result getAllUsers() {
        return new Result().success(userService.getAllUsers());
    }


    // 添加用户
    @PostMapping("/add")
    //@ResponseBody
    public Result getById(@RequestParam("name") String name, @RequestParam("tel") String tel) {
        User user = new User();
        user.setName(name);
        user.setTel(tel);
        return new Result().success(userService.addUser(user));
    }

    ///=========测试案例=======
    @RequestMapping("/text") ///拦截其他地址，只允许本机访问
    public ResponseEntity<?> localEndpoint(HttpServletRequest request, @RequestParam("name") String name) {
        String remoteAddr = request.getRemoteAddr();

        if (!"127.0.0.1".equals(remoteAddr) && !"localhost".equals(request.getServerName())) {
            return ResponseEntity.status(HttpStatus.NOT_FOUND).build();
        }

        Map<String, Object> map = new HashMap<>();
        map.put("code", 200);
        map.put("date", "成功");
        map.put("name", name);
        map.put("msg", "only localhost can access");

        // 接口逻辑处理
        return ResponseEntity.ok(map);
    }

}